package net.pimpas.web.jsf.renderers.message.ajax;

import java.io.IOException;
import java.util.Iterator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIMessage;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import net.pimpas.web.jsf.renderers.AjaxRendererBase;
import net.pimpas.web.jsf.renderers.RendererBase;
import net.pimpas.web.jsf.util.ComponentUtils;

public class AjaxMessageRenderer extends RendererBase implements AjaxRendererBase {
	
	public static final String JAVASCRIPT_HANDLER		= "pimpas.AJAX.Populate.Html";
	
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		if(!component.isRendered()) return;
		if(!ComponentUtils.isCorrectComponentType(component, UIMessage.class)) return;
		
		UIMessage cp = (UIMessage) component;
		String serverID = cp.getFor();
		UIComponent target = ComponentUtils.getComponentById(context.getViewRoot(), context, serverID, ComponentUtils.SERVER_ID);
		if(target == null) {
			// TODO skip
			return;
		}
		
        ResponseWriter writer = context.getResponseWriter();
        
		String clientID = target.getClientId(context);
		Iterator it = context.getMessages(clientID);
		writer.startElement("success", cp);
		writer.write(it.hasNext() ? "false" : "true");
		writer.endElement("success");
		writer.startElement("value", cp);
		
		if(it.hasNext()) {
			FacesMessage message = (FacesMessage) it.next();
			writer.write(message.getDetail());
		}
		
		writer.endElement("value");
	}

	public String getJavascriptHandler() {
		return JAVASCRIPT_HANDLER;
	}

	public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
	}

	public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
	}
}